"""
Case Type   : 资源池化
Case Name   : 系统函数query_node_reform_info函数，节点切换后验证功能
Create At   : 2024.6
Owner       : haomeng
Description :
    1、备节点查询集群reform相关统计信息
    2、switchover使备节点升主
    3、在新主节点查询reform相关统计信息
    4、恢复集群初始状态
Expect      :
    1、查询失败，备节点不支持
    2、switchover切换成功
    3、查看reform信息成功，新主节点reform_type为switchover
    4、恢复集群初始状态成功
"""


import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class SharedStorage(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.error_msg = 'ERROR:  [SS] cannot query query_node_reform_info' \
                         ' at Standby node while DMS enabled!'

        self.log.info('------检查数据库状态是否正常------')
        status = self.pri_sh.exec_cm_ctl('query', '-Cv')
        self.assertIn("cluster_state   : Normal", status)

    def test_innerfunc(self):
        text = '-----step1:备节点查询集群reform相关统计信息; expect:查询失败，备节点不支持-----'
        self.log.info(text)

        sql = 'select * from query_node_reform_info();'
        self.log.info(sql)
        res1 = self.sta_sh.execut_db_sql(sql)
        self.log.info(res1)
        self.assertIn(self.error_msg, res1, '查看reform统计信息成功')

        text = '-----step2:switchover使备1节点升主; expect:switchover操作成功-----'
        self.log.info(text)

        switch_dn = self.pri_sh.exec_cm_ctl('switchover', '-n 2',
                                            f'-D {macro.DB_INSTANCE_PATH}')
        self.log.info(switch_dn)
        self.assertIn(self.constant.cm_switchover_success_msg, switch_dn,
                      'switchover操作失败')

        text = '-----step3:在新主节点查询reform相关统计信息; ' \
               'expect:查看reform信息成功，新主节点reform_type为switchover-----'
        self.log.info(text)

        res2 = self.sta_sh.execut_db_sql(sql)
        self.log.info(res2)
        self.assertIn('1', res2.splitlines()[3].split('|')[0], 'node_id不一致')
        self.assertIn('Switchover', res2.splitlines()[3].split('|')[1],
                      'reform_type不一致')

    def tearDown(self):
        text = '-----step4:恢复集群初始状态; expect:恢复初始状态成功-----'
        self.log.info(text)

        start_dn = self.pri_sh.exec_cm_ctl('start')
        self.log.info(start_dn)

        recovery_dn = self.pri_sh.exec_cm_ctl('switchover', '-a')
        self.log.info(recovery_dn)
        self.assertIn(self.constant.cm_start_success_msg, start_dn,
                      '拉起集群失败')
        self.assertIn(self.constant.cm_switchover_success_msg, recovery_dn,
                      '恢复集群初始状态失败')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
